import { useState } from 'react';
import Cubox from './Cubox';

import colorScheme from './color-scheme';

import * as styles from './Select.module.css';

export default function CuboxSelect ({value="", suggs=[], onChange=e=>{}, onSelectOption=e=>{}, isDisabledEditing, isDisabled, color='blue', style, placeholder}) {

  const [back, fore, text] = isDisabled
  ? ['base01', 'base01', 'base06']  
  : [color, 'base00', 'base06'];

  const [isFocused, setFocused] = useState(false);

  const QBOXProps = {
		cornerRadius: 20,
		strokeWidth: 1, 
		isOutlined: true,
		backColor: colorScheme[back],
		foreColor: colorScheme[fore],
    corners: isFocused > 0 ? {BR:'L', BL:'L'} : {},
    style: {width: '100%'}
	};

  const inputStyle = {
    color:colorScheme[text],
  }

  const select = (e, sugg) => {
    e.stopPropagation();
    e.preventDefault();
    onSelectOption(e, sugg);
    setFocused(false);
  }

  const blur = function (e) {
    e.stopPropagation();
    e.preventDefault();
    setFocused(false);
  }

  const toggleFocus = () => {
    if (!isDisabled) {
      setFocused(!isFocused);
    }
  }

  const suggProps = {
    ...QBOXProps,
    corners:{TR:'L', TL:'L'},
    style:{
      position:'absolute',
      top:40,
      zIndex: 9999,
      background: 'white',
      width: '100%',
    }
  }

  const inputProps = {
    placeholder,
    spellCheck: false,
    value: value?.desc ?? value,
    onChange,
    className:styles['select'],
    style: inputStyle,
    disabled: isDisabledEditing || isDisabled,
    onBlur: blur,
  }

  const actualSuggs =Array.isArray(suggs)
    ? suggs
    : suggs(value)

  const suggElems = actualSuggs.map((sugg, i) => <option key={i} className={styles['option']} onMouseDown={(e) => select(e, sugg)} value={sugg?.value ?? sugg}>{sugg?.desc ?? sugg}</option>)

  const suggsList = isFocused
  ? <Cubox {...suggProps}>
      <div className={styles['option-wrapper']}>
      {suggElems}
      </div>
    </Cubox>

  : <div></div>
  
  return <div onClick={toggleFocus} style={{position: 'relative', ...style}}>
    <Cubox {...QBOXProps} >
      <input {...inputProps} />
    </Cubox>
    {suggsList}
  </div>
}